package com.demo.simple2;

import java.util.function.BiFunction;

import org.reactivestreams.Publisher;

import io.netty.handler.codec.LineBasedFrameDecoder;
import reactor.core.publisher.Flux;
import reactor.netty.DisposableServer;
import reactor.netty.NettyInbound;
import reactor.netty.NettyOutbound;
import reactor.netty.tcp.TcpServer;
import reactor.util.Logger;
import reactor.util.Loggers;

public class ServerDemo {
	final static Logger log     = Loggers.getLogger(ServerDemo.class);

	public static void main(String[] args) {
		BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>> serverHandler = (in, out) -> {
			in.receive()
				.asString()
				.subscribe(data -> {
					log.info("data " + data + " on " + in);
				});
			return Flux.never();
		};

		DisposableServer server =
                TcpServer.create()
                         .host("localhost")
                         .port(8080)
                         .handle(serverHandler)
                         .doOnConnection(c -> {
                        	 // 在有新的客户端连接上来后，注册handler
                        	 c.addHandlerLast("codec", new LineBasedFrameDecoder(8 * 1024));
                         })
                         .bindNow();

        server.onDispose().block();
	}

}
